<template>
    <div id="UserManagement">
        <div>
            <el-card class="box-card">
                <el-row>
                    <el-col :span="3"> 
                        <el-input
                            placeholder="请输入用户名称"
                            v-model="userName"
                            clearable>
                        </el-input>
                    </el-col>
                    <el-col :span="3" :push="1"> 
                        <el-input
                        placeholder="请输入登录名称"
                        v-model="loginName"
                        clearable>
                        </el-input>
                    </el-col>
                    <el-col :span="3" :push="2" > 
                        <el-select  v-model="sex" placeholder="请选择性别">
                            <el-option
                                v-for="item in sexOptions"
                                :key="item.id"
                                :label="item.sex"
                                :value="item.sex"
                                >
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="3" :push="3" > 
                        <el-input
                        placeholder="请输入角色名称"
                        v-model="roleName"
                        clearable>
                        </el-input>
                    </el-col>
                    <el-col :span="3" :push="4" > 
                        <el-input
                        placeholder="请输入年龄"
                        v-model="age"
                        oninput="value=value.replace(/[^0-9]/g,'')"
                        clearable>
                        </el-input>
                    </el-col>
                    <el-col :span="2" :offset="1"  :push="4"><el-button icon="el-icon-search" @click="getUserByPage" circle></el-button></el-col>
                    <el-col :span="2" :push="4"><el-button type="primary" @click="addProduct" round>新增</el-button></el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-table
                            :data="productData"
                            border
                            style="width:100%">
                            <el-table-column
                            fixed
                            prop="id"
                            label="序号"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="loginName"
                            label="登录名称"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="userName"
                            label="用户名称"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="name"
                            label="真实姓名"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="age"
                            label="年龄"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="sex"
                            label="性别"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="roleId"
                            label="角色"
                            >
                            <template slot-scope="scope">
                                <el-col v-for='item in options' :key='item.id'>
                                <el-col v-if="item.id == scope.row.roleId">
                                    {{item.roleName}}
                                </el-col>
                                </el-col>
                            </template>
                            </el-table-column>
                            <el-table-column
                            prop="createTime"
                            label="创建时间"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="avatarId"
                            label="头像id"
                            >
                            <template slot-scope="scope">
                            <el-image
                                style="width: 70px; height: 70px"
                                shape="square"
                                :src='`http://127.0.0.1:8082/getImageById?id=${scope.row.avatarId}`'
                                fit="fill">
                                </el-image>
                            </template>
                            </el-table-column>
                            <el-table-column
                            fixed="right"
                            label="操作"
                            width="200">
                            <template slot-scope="scope">
                                <el-button @click="handleClick(scope.row)" type="text" size="small" >查看</el-button>
                                <el-button @click="handleUpdate(scope.row)" type="text" size="small">编辑</el-button>
                                <el-button @click="deleteUser(scope.row)" type="text" size="small" style="color: red;">删除</el-button>
                            </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row style="text-align: center;">
                    <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage4"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="page.total">
                    </el-pagination>          
                </el-row>
            </el-card>
            <!-- 数据新增功能 -->
            <el-dialog title="新增用户" :visible.sync="dialogFormVisible" @close="handleClose('productForm')">
                <el-form :model="productForm" :rules="rules" ref="productForm">
                    <!--上传图片-->
                    <el-upload
                        style="text-align: center;"
                        class="avatar-uploader"
                        action="http://127.0.0.1:8082/uploadPicture"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    <el-form-item label="用户名称" :label-width="formLabelWidth" prop="userName">
                        <el-input v-model="productForm.userName" autocomplete="off" ></el-input>
                    </el-form-item>
                    <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
                        <el-input v-model="productForm.password" autocomplete="off" ></el-input>
                    </el-form-item>
                    <el-form-item label="登录名称" :label-width="formLabelWidth" prop="loginName">
                        <el-input v-model="productForm.loginName" autocomplete="off" ></el-input>
                    </el-form-item>
                    <el-form-item label="本人真实姓名" :label-width="formLabelWidth" prop="name">
                        <el-input v-model="productForm.name" autocomplete="off" ></el-input>
                    </el-form-item>
                    <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
                        <el-input v-model="productForm.age" autocomplete="off" oninput="value=value.replace(/[^0-9]/g,'')"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
                        <el-input v-model="productForm.sex" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色" :label-width="formLabelWidth" prop="roleId">
                        <el-select v-model="productForm.roleId" placeholder="请选择">
                            <el-option
                                v-for="item in options"
                                :key="item.id"
                                :label="item.roleName"
                                :value="item.id"
                                @click.native="choiceRole(item.roleName)">
                            </el-option>
                            </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveUser('productForm')">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 数据查看功能 -->
            <el-dialog title="查看详情" :visible.sync="dialogFormVisibleDatil">
                <el-upload
                    class="avatar-uploader"
                    action="http://127.0.0.1:8080/userMassage/File"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :disabled="true">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <el-form :model="productFormList">
                    <el-form-item label="用户名" :label-width="formLabelWidth">
                        <el-input v-model="productFormList.userName" autocomplete="off"  :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="登录名" :label-width="formLabelWidth">
                        <el-input v-model="productFormList.loginName" autocomplete="off"  :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" :label-width="formLabelWidth">
                        <el-input v-model="productFormList.password" autocomplete="off"  :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="真实姓名" :label-width="formLabelWidth">
                        <el-input v-model="productFormList.name" autocomplete="off"  :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="年龄" :label-width="formLabelWidth">
                        <el-input v-model="productFormList.age" autocomplete="off"  :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth">
                        <el-input v-model="productFormList.sex" autocomplete="off"  :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="用户角色" :label-width="formLabelWidth">
                        <el-select v-model="productFormList.roleId" placeholder="请选择">
                            <el-option
                            v-for="item in options"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id"
                            :disabled="true">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisibleDatil = false">关闭</el-button>
                </div>
            </el-dialog>
            <!-- 数据修改功能 -->
            <el-dialog title="用户编辑" :visible.sync="dialogFormVisibleUpdate" @close="handleClose('productFormEdit')">
                    <el-form :model="productFormEdit" :rules="rules" ref="productFormEdit">
                        <el-upload
                            style="text-align: center;"
                            class="avatar-uploader"
                            action="http://127.0.0.1:8082/uploadPicture"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <el-form-item label="用户名称" :label-width="formLabelWidth" prop="userName">
                            <el-input v-model="productFormEdit.userName" autocomplete="off" ></el-input>
                        </el-form-item>
                        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
                            <el-input v-model="productFormEdit.password" autocomplete="off" ></el-input>
                        </el-form-item>
                        <el-form-item label="登录名称" :label-width="formLabelWidth" prop="loginName">
                            <el-input v-model="productFormEdit.loginName" autocomplete="off" ></el-input>
                        </el-form-item>
                        <el-form-item label="本人真实姓名" :label-width="formLabelWidth" prop="name">
                            <el-input v-model="productFormEdit.name" autocomplete="off" ></el-input>
                        </el-form-item>
                        <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
                            <el-input v-model="productFormEdit.age" autocomplete="off" oninput="value=value.replace(/[^0-9]/g,'')"></el-input>
                        </el-form-item>
                        <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
                            <el-input v-model="productFormEdit.sex" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="角色" :label-width="formLabelWidth" prop="roleId">
                            <el-select v-model="productFormEdit.roleId" placeholder="请选择">
                                <el-option
                                    v-for="item in options"
                                    :key="item.id"
                                    :label="item.roleName"
                                    :value="item.id"
                                    @click.native="choiceRole(item.roleName)">
                                </el-option>
                                </el-select>
                        </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisibleUpdate = false">取 消</el-button>
                    <el-button type="primary" @click="updateUser('productFormEdit')">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>
<script>
const axios = require('axios');
export default {
   name: 'UserManagement',
        data(){
            //新增修改性别校验
            var sex = (rule, value, callback) => {
                if (value === '') {
                callback(new Error('请输入性别'));
                } else if(value ==="男" || value ==="女"){
                    callback();
                
                }else{
                    callback(new Error('请输入男或者女'));
                }
            };
            //新增修改性别校验
            var age = (rule, value, callback) => {
                if(value==='0' || value>100){
                    callback(new Error('请输入正确的年龄'));
                }
                else if(value===''){
                    callback(new Error('请输入年龄'));
                }
                else{
                     callback();
                }
            };
            //新增修改账号校验
            var loginName = (rule, value, callback) => {
                if(value !=='' ){
                    if(this.checkLoginNameEdit === value){
                        callback();
                    }
                    else{
                        //新增弹窗检查景区是否重复
                        axios.get("http://127.0.0.1:8082/userManagement/checkLoginName?loginName="+value).then(res=>{
                            this.check= res.data.obj
                            if (this.check) {
                                callback(new Error('该账号已存在'));
                            } else {
                                callback();
                            }
                        })
                    }
                }
                else{
                     callback();
                }
            };
            return {
                //用于修改校验登录账号
                checkLoginNameEdit:'',
                //新增修改登录账号校验
                check:[],
                //模糊查年龄
                age:'',
                //模糊查角色名称
                roleName:'',
                //新增方法存放roleName
                saveRoleName:'',
                //模糊查性别
                sex:'',
                //模糊查登录名称
                loginName:'',
                //模糊查用户名称
                userName:"",
                imageFile:File,
                productData: [],
                //新增弹框true弹出
                dialogFormVisible: false,
                //查看弹框true弹出
                dialogFormVisibleDatil:false,
                //修改弹框true弹出
                dialogFormVisibleUpdate:false,
                // 新增时使用到的form对象
                productForm: {
                    id:"",
                    userName:"",
                    password:"",
                    loginName:"",
                    age:"",
                    sex:"",
                    name:"",
                    roleId:"",
                    roleName:'',
                },
                // 新增时使用到的form对象
                roleForm: {
                    id:"",
                    roleName:"",
                },
                //查看时使用到的form对象
                productFormList:{
                    id:"",
                    userName:"",
                    password:"",
                    loginName:"",
                    age:"",
                    sex:"",
                    name:"",
                    roleId:""
                },
                // 修改时使用到的form对象
                productFormEdit:{
                    id:"",
                    userName:"",
                    password:"",
                    loginName:"",
                    age:"",
                    sex:"",
                    name:"",
                    roleId:"",
                    avatarId:"",
                    roleName:'',
                },
                formLabelWidth: '120px',
                imageUrl:"",
                //分页当前选中页
                currentPage4: 1,
                page:{
                    pageSize:10,//条数
                    pageNum:1,//页数
                    total:0
                },
                tatal:0,
                filterText: '',
                    data: [],
                    options: [],
                    defaultProps: {
                children: 'childs',
                label: 'departmentName'
                },
                sexOptions:[
                    {
                        id:1,
                        sex:'男'
                    },
                    {
                        id:2,
                        sex:'女'
                    }
                ],
                //用户新增修改校验规则
                rules:{
                    userName: [
                        { required: true, message: '请输入用户名称', trigger: 'blur' },
                        { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 2, max: 32, message: '长度在 2 到 30个字符', trigger: 'blur' }
                    ],
                    name: [
                        { required: true, message: '请输入真实姓名', trigger: 'blur' },
                        { min: 2, max: 8, message: '长度在 2 到 8 个中文汉字', trigger: 'blur' }
                    ],
                    loginName: [
                        { required: true, message: '请输入账号', trigger: 'blur' },
                        { min: 2, max: 8, message: '长度在 2 到 8 英文或数字', trigger: 'blur' },
                        { validator: loginName, trigger: 'blur' } 
                    ],
                    sex: [
                        { validator: sex, trigger: 'blur' } 
                    ],
                    age: [
                        { validator: age, trigger: 'blur' },
                    ],
                    roleId: [
                            { required: true, message: '请选择角色', trigger: 'blur' },
                    ]

                }
            }
        },
        methods:{    
            //新增清空值
            handleClose(formName) {
                this.$refs[formName].resetFields()// 重置数据，同时也取消了表单的校验 refundFormData：el-form用ref绑定的值，
            },   
            //新增赋值角色名称
            choiceRole(roleName){
                this.saveRoleName = roleName
            },
            // 分页
            handleSizeChange(ps) {
              this.page.pageSize=ps;
              this.getUserByPage()
              console.log(`每页 ${val} 条`);
             },
            handleCurrentChange(pn) {
              this.page.pageNum=pn;
              this.getUserByPage()
             
            },
          //查询角色
            getRoleName(){
               axios.get("http://127.0.0.1:8082/role/getRoleName",this.roleForm)
                  .then(res=>{
                    this.options=res.data.obj
                    console.log(this.options)
                  }).catch(error => {
                        this.$message.error('服务器崩溃了，请稍后再尝试使用！');
                    })
            },
          //用户分页查+模糊查（真实姓名）
            getUserByPage () {
              axios.get('http://127.0.0.1:8082/userManagement/userAllList', {
                  params: {
                    loginName:this.loginName,
                    userName: this.userName,
                    sex: this.sex,
                    roleName: this.roleName,
                    pageSize: this.page.pageSize,
                    pageNum: this.page.pageNum,
                    age : this.age
                  }
                })
                .then((res) => {
                  this.productData = res.data.content
                  this.page.total = res.data.total
                })
            },
            // 图片上传之后的方法
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            // 图片上传之前的校验方法
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/png' || 'image/jpg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                this.imageFile = file
                this.imageUrl = URL.createObjectURL(file);
                return false;
            },
            //新增用户
            saveUser(formName){ 
                var formdata = new FormData();
                formdata.set("userName",this.productForm.userName)
                formdata.set("password",this.productForm.password)
                formdata.set("loginName",this.productForm.loginName)
                formdata.set("age",this.productForm.age)
                formdata.set("sex",this.productForm.sex)
                formdata.set("name",this.productForm.name)
                formdata.set("roleId",this.productForm.roleId)
                formdata.set("roleName",this.saveRoleName)
                if(this.imageFile.name!="File"){
                    formdata.set("file",this.imageFile,this.imageFile.name)
                }
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.post("http://127.0.0.1:8082/userManagement/saveUser",formdata).
                        then(res => {
                            if(res.data.obj>0){
                                this.message("恭喜你，保存数据成功！","success")
                                this.dialogFormVisible = false
                                this.imageUrl=""
                                this.imageFile=File
                                this.productForm={
                                    userName:"",
                                    loginName:"",
                                    password:"",
                                    age:"",
                                    sex:"",
                                    name:""
                                }
                                this.getUserByPage()
                            }else{
                                this.message("对不起，保存失败！","warning")
                            }
                        }).catch(error => {
                            this.$message.error('服务器崩溃了，请稍后再尝试使用！');
                        })
                    } else {
                        return false;
                    }
                });
            },
            //修改用户
            updateUser(formName){
                var formdata = new FormData();
                formdata.set("id",this.productFormEdit.id)
                formdata.set("userName",this.productFormEdit.userName)
                formdata.set("password",this.productFormEdit.password)
                formdata.set("loginName",this.productFormEdit.loginName)
                formdata.set("age",this.productFormEdit.age)
                formdata.set("sex",this.productFormEdit.sex)
                formdata.set("name",this.productFormEdit.name)
                formdata.set("roleId",this.productFormEdit.roleId)
                formdata.set("avatarId",this.productFormEdit.avatarId)
                formdata.set("roleName",this.saveRoleName)
                if(this.imageFile.name!="File"){
                    formdata.set("file",this.imageFile,this.imageFile.name)
                }
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.put("http://127.0.0.1:8082/userManagement/updateUser",formdata)
                        .then(res=>{
                            if(res.data.code==='200'){
                            this.message("恭喜你，修改数据成功！","success")
                                    this.dialogFormVisibleUpdate = false
                                    this.imageUrl = ''
                                    this.imageFile=File
                                    this.productFormEdit={
                                        userName:"",
                                        loginName:"",
                                        password:"",
                                        age:"",
                                        sex:"",
                                        name:""
                                    }
                                    this.getUserByPage();// 重新渲染数据列表
                            }else{
                                    this.message("对不起，修改失败！","warning")
                                }
                            }).catch(error => {
                                this.$message.error('服务器崩溃了，请稍后再尝试使用！');
                        })
                    } else {
                        return false;
                    }
                });
                
            },
            //删除用户
            deleteUser(row){
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }//删除提示框
                ).then(() => {
                    axios.delete("http://127.0.0.1:8082/userManagement/deleteUser?id="+row.id)
                .then(res =>{
                    if(res.data.code==='200' ){
                        this.message("恭喜你，删除成功！","success")
                        this.getUserByPage()
                    }else{
                        this.message('删除失败','warning')
                    }
                }).catch(error =>{
                        alert(error)
                })
                }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
                });
            },
            //消息提示框
            message(message,type){
                this.$message({
                message:message,
                type: type
                });
            },
            //查看按钮回显
            handleClick(row){
                this.dialogFormVisibleDatil = true
                this.productFormList.userName=row.userName
                this.productFormList.loginName=row.loginName
                this.productFormList.password=row.password
                this.productFormList.name=row.name
                this.productFormList.age=row.age
                this.productFormList.sex=row.sex
                this.productFormList.avatarId=row.avatarId
                    this.productFormList.roleId=row.roleId
                this.imageUrl='http://127.0.0.1:8082/getImageById?id='+row.avatarId
            },
            //修改按钮回显
            handleUpdate(row){
                this.imageUrl='http://127.0.0.1:8082/getImageById?id='+row.avatarId
                this.dialogFormVisibleUpdate=true
                this.productFormEdit.id = row.id
                this.productFormEdit.userName=row.userName
                this.productFormEdit.password=row.password
                this.productFormEdit.loginName=row.loginName
                this.checkLoginNameEdit = row.loginName
                this.productFormEdit.age=row.age
                this.productFormEdit.sex=row.sex
                this.productFormEdit.name=row.name
                this.productFormEdit.roleId=row.roleId
                this.productFormEdit.avatarId=row.avatarId
            },
            //新增按钮弹框
            addProduct(){
                this.dialogFormVisible = true
                this.imageUrl=""
            }
        },
        mounted(){
            
            this.getRoleName()//角色类型查询
            this.getUserByPage()//分页全查+模糊查（用户名）
        }, 
}
</script>
<style>
/**
* 附件上传样式
*/
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
.el-icon-arrow-down {
    font-size: 12px;
}
.box-card {
    height: 100%;
}
</style>